package com.truyentranh.modules.haivl;

import java.io.IOException;
import java.util.ArrayList;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
import android.widget.TabHost.TabSpec;
import android.widget.TabWidget;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.BaseDialogListener;
import com.facebook.android.BaseRequestListener;
import com.facebook.android.Facebook;
import com.facebook.android.FacebookError;
import com.facebook.android.LoginButton;
import com.facebook.android.SessionEvents;
import com.facebook.android.SessionEvents.AuthListener;
import com.facebook.android.SessionEvents.LogoutListener;
import com.facebook.android.SessionStore;
import com.facebook.android.Utility;
import com.truyentranh.R;
import com.truyentranh.controls.AdsViewControl;
import com.truyentranh.controls.IOnComicChanged;
import com.truyentranh.controls.IOnFinalPage;
import com.truyentranh.controls.ImagePagerAdapter;
import com.truyentranh.controls.OnSaveComic;
import com.truyentranh.controls.ViewPagerSupportImageView;
import com.truyentranh.controls.onSocialAction;
import com.truyentranh.data.HaiBLMetalData;
import com.truyentranh.main.AdsBussiness;
import com.truyentranh.main.ComicBussiness;
import com.truyentranh.main.DisplayUtils;
import com.truyentranh.main.MainApplication;
import com.truyentranh.modules.local.MoreActivity;
import com.truyentranh.network.APIRequestWorker;
import com.truyentranh.network.Request;
import com.truyentranh.network.RequestListener;
import com.truyentranh.requester.HaiVLRequester;
import com.truyentranh.utils.AppSettingParams;
import com.truyentranh.utils.FaceBookUtils;
import com.truyentranh.utils.Logger;
import com.truyentranh.utils.Utils;
import com.truyentranh.utils.sqllite.datasource.TopicHaiBlData;

public class HaiVLActivity extends Activity implements OnTabChangeListener, IOnFinalPage, onSocialAction, IOnComicChanged {

	private TabHost tabHost;
	private ImagePagerAdapter imageComicAdapter;
	private FrameLayout topMenuBar;

	private String currentTab = "";
	private int newPage = 1;
	private int hotPage = 1;
	private int oldPage = 1;
	private long currentRequestId = -1;

	protected void onDestroy() {
		if (imageComicAdapter != null) {
			imageComicAdapter.clearListener();
		}
		tabHost.removeAllViewsInLayout();
		tabHost.removeAllViews();
		tabHost.destroyDrawingCache();
		super.onDestroy();
	}

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);

		// Remove notification bar
		this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
		setContentView(R.layout.haivl_activity_layout);
		init();

		tabHost = (TabHost) findViewById(android.R.id.tabhost);
		tabHost.setup();
		tabHost.setOnTabChangedListener(this);

		final TabWidget tabWidget = tabHost.getTabWidget();
		FrameLayout tabContent = tabHost.getTabContentView();

		View[] originalTextViews = new View[tabWidget.getTabCount()];
		for (int index = 0; index < tabWidget.getTabCount(); index++) {
			originalTextViews[index] = (View) tabWidget.getChildTabViewAt(index);
		}
		tabWidget.removeAllViews();

		for (int index = 0; index < tabContent.getChildCount(); index++) {
			tabContent.getChildAt(index).setVisibility(View.GONE);
		}

		for (int index = 0; index < originalTextViews.length; index++) {
			final View tabContentView = tabContent.getChildAt(index);
			String tag = "";
			String name = "";
			if (index == 0) {
				tag = "new";
				name = "Mới nhất";
			} else if (index == 1) {
				tag = "hot";
				name = "Nóng hổi";
			} else if (index == 2) {
				tag = "old";
				name = "�?ào mộ";
			}
			TabSpec tabSpec = tabHost.newTabSpec(tag);
			View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, tabWidget, false);
			TextView title = (TextView) tabIndicator.findViewById(R.id.title);
			title.setText(name);
			// ImageView icon = (ImageView)
			// tabIndicator.findViewById(R.id.icon);
			// icon.setImageResource(resourceId);
			tabSpec.setIndicator(tabIndicator);

			tabSpec.setContent(new TabContentFactory() {
				public View createTabContent(String tag) {
					return tabContentView;
				}
			});
			tabHost.addTab(tabSpec);
		}

//		initActionBar();
		topMenuBar = (FrameLayout) findViewById(R.id.top_menu_bar);

		TextView textView = (TextView) findViewById(R.id.titleActivity);
		textView.setText("Hài vui lắm");

		final Button moreFunction = (Button) findViewById(R.id.btnMoreFunctions);
		if (moreFunction != null) {
			moreFunction.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					openOptionsMenu();
					// mQuickAction.show(v);
					// mQuickAction.setAnimStyle(QuickAction.ANIM_GROW_FROM_RIGHT);
				}
			});
		}
		Button back = (Button) findViewById(R.id.btnBackAcvitity);
		if (back != null) {
			back.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					finish();
				}
			});
		}
	}

	void doShareAuth() {
		// mLoginButton.doIt();
	}

	void doAdsByServer() {
		AdsBussiness.getInstance().doGetAdsFromServer(this, prView);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		int itemId = item != null ? item.getItemId() : -1;
		switch (itemId) {
		case 1:
			Logger.logMe("Save default");
			ComicBussiness.getInstance(HaiVLActivity.this).doSaveCommicToDefault(HaiVLActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {

				public void onError(int errorCode) {
					processError(errorCode);
				}

				public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
					// TODO Auto-generated
					// method stub

				}

				public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
					Logger.logMe("Sai flow, chuyen gi da xay ra duoi tang bussiness");
				}
			});
			break;
		case 2:
//			Logger.logMe("Save ");
//			ComicBussiness.getInstance(HaiVLActivity.this).doSaveCommic(HaiVLActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {
//
//				public void onError(int errorCode) {
//					processError(errorCode);
//				}
//
//				public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//					// TODO Auto-generated
//					// method stub
//
//				}
//
//				public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//					if (haiBlData != null) {						
//						showNotice("Thông báo", "�?ã dùng \"" + haiBlData.getName() + "\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi"
//								+ " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
//					}
//				}
//			});
//			break;
			Utils.downloadPhoto(this, 0, this, imageComicAdapter.getCurrentData().getImageUrl(), getResources());
			break;
		case 3:
			Logger.logMe("facebook");
			FaceBookUtils.doShareFaceBook(imageComicAdapter.getCurrentData(), HaiVLActivity.this);
			break;
		case 4:
			doRefreshPage();
			Logger.logMe("refresh");
			break;
		case 5 :
			FaceBookUtils.doShareApplication(this);
			break;
		case 6 :
			doComment(imageComicAdapter.getCurrentData());
			break;
		case 7 :
			Utils.setWallpaper(this, 0, this,  imageComicAdapter.getCurrentData().getImageUrl(), getResources());
			break;
			
		}
		// TODO Auto-generated method stub
		return super.onMenuItemSelected(featureId, item);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		if (ComicBussiness.getInstance(this).getDefaultComicTopic() != null && ComicBussiness.getInstance(this).getDefaultComicTopic().getId() != -1) {
			menu.add(1, 1, 1, "Lưu " + ComicBussiness.getInstance(this).getDefaultComicTopic().getName()).setIcon(R.drawable.ic_save_default);
		}
		menu.add(1, 2, 2, "Lưu").setIcon(R.drawable.ic_saved);
		menu.add(3, 3, 3, "Facebook").setIcon(R.drawable.ic_facebook);
		menu.add(4, 4, 4, "Tải lại").setIcon(R.drawable.ic_refresh);
		
		menu.add(5, 5, 5, "Chia sẻ App").setIcon(R.drawable.ic_share);
		menu.add(5, 6, 6, "Bình luận").setIcon(R.drawable.ic_comment);
		menu.add(6, 7, 5, "�?ặt hình n�?n").setIcon(R.drawable.ic_wall);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			return true;
		}

		return super.onKeyDown(keyCode, event);
	}

	void processError(int errorCode) {
		String error = "";
		switch (errorCode) {

		case OnSaveComic.CREATE_TOPIC_ERROR:
			error = "Không thể tạo được chủ đ�?.";
			break;
		case OnSaveComic.DB_NOT_FOUND:
			error = "Không tìm thấy tập tin dữ liệu.";
			break;
		case OnSaveComic.DEFAULT_TOPIC_NOTFOUND:
			error = "Không tìm thấy chủ đ�? mặc định.";
			break;
		case OnSaveComic.IMAGE_NOT_FOUND:
			error = "Không có truyện hiển thị.";
			break;
		case OnSaveComic.INSERT_COMIC_ERROR:
			error = "Không thể thêm truyện vào máy.";
			break;
		case OnSaveComic.TOPIC_NAME_INVAILD:
			error = "Tên chủ đ�? không đúng.";
			break;
		case OnSaveComic.TOPIC_NOTFOUND:
			error = "Không tìm thấy chủ đ�?.";
			break;
		}
		if (!error.equals("")) {
			Toast.makeText(HaiVLActivity.this, error, 1000).show();
		}
	}

	void showNotice(String title, String message) {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(title);
		builder.setMessage(message);
		builder.setPositiveButton("�?óng", null);

		AlertDialog notice = builder.create();
		notice.show();
	}

	void doRefreshPage() {
		onTabChanged(currentTab);
	}

//	void initActionBar() {
//		mQuickAction = QuickAction.getCommonActionBar(HaiVLActivity.this, ComicBussiness.getInstance(this).getDefaultComicTopic(), new OnActionItemClickListener() {
//
//			public void onItemClick(int pos) {
//				if (ComicBussiness.getInstance(HaiVLActivity.this).getDefaultComicTopic() == null) {
//					if (pos == 0) {
//						ComicBussiness.getInstance(HaiVLActivity.this).doSaveCommic(HaiVLActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {
//
//							public void onError(int errorCode) {
//								processError(errorCode);
//							}
//
//							public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								// TODO Auto-generated
//								// method stub
//
//							}
//
//							public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								if (haiBlData != null) {
//									initActionBar();
//									showNotice("Thông báo", "�?ã dùng \"" + haiBlData.getName() + "\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi"
//											+ " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
//								}
//							}
//						});
//					} else if (pos == 1) {
//						// FaceBookUtils.doShareFaceBook(imageComicAdapter.getCurrentData(),
//						// HaiVLActivity.this);
//						FaceBookUtils.doShareFaceBook(imageComicAdapter.getCurrentData(), HaiVLActivity.this);
//					} else if (pos == 2) {
//						doRefreshPage();
//					} else if (pos == 3) {
//						FaceBookUtils.makeFriend(imageComicAdapter.getCurrentData(), HaiVLActivity.this);
//					}
//				} else {
//					if (pos == 0) {
//						ComicBussiness.getInstance(HaiVLActivity.this).doSaveCommicToDefault(HaiVLActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {
//
//							public void onError(int errorCode) {
//								processError(errorCode);
//							}
//
//							public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								// TODO Auto-generated
//								// method stub
//
//							}
//
//							public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								Logger.logMe("Sai flow, chuyen gi da xay ra duoi tang bussiness");
//							}
//						});
//					} else if (pos == 1) {
//						ComicBussiness.getInstance(HaiVLActivity.this).doSaveCommic(HaiVLActivity.this, imageComicAdapter.getCurrentData(), new OnSaveComic() {
//
//							public void onError(int errorCode) {
//								processError(errorCode);
//							}
//
//							public void onDone(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								// TODO Auto-generated
//								// method stub
//
//							}
//
//							public void onDoneWithNewTopic(HaiBLMetalData blMetalData, TopicHaiBlData haiBlData) {
//								if (haiBlData != null) {
//									initActionBar();
//									showNotice("Thông báo", "�?ã dùng \"" + haiBlData.getName() + "\" làm chủ đ�? lưu mặc định.\nTip : Bạn có thể thay đổi"
//											+ " chủ đ�? mặc định này trong phần thiết lập của ứng dụng");
//								}
//							}
//						});
//					} else if (pos == 2) {
//						// FaceBookUtils.doShareFaceBook(imageComicAdapter.getCurrentData(),
//						// HaiVLActivity.this);
//						FaceBookUtils.doShareFaceBook(imageComicAdapter.getCurrentData(), HaiVLActivity.this);
//					} else if (pos == 3) {
//						doRefreshPage();
//					} else if (pos == 4) {
//						FaceBookUtils.makeFriend(imageComicAdapter.getCurrentData(), HaiVLActivity.this);
//					}
//				}
//
//			}
//		});
//	}

	void init() {
	}

	void getNew(RequestListener listener) {
		Logger.logMe("requesting page = " + newPage);
		HaiVLRequester haiVLRequester = HaiVLRequester.getNew(newPage, listener);
		currentRequestId = AppSettingParams.nextRequestId();
		haiVLRequester.setRequestId(currentRequestId);
		APIRequestWorker.getInstance().addAPIRequest(haiVLRequester);
	}

	void getHot(RequestListener listener) {
		Logger.logMe("requesting page = " + hotPage);
		HaiVLRequester haiVLRequester = HaiVLRequester.getHot(hotPage, listener);
		currentRequestId = AppSettingParams.nextRequestId();
		haiVLRequester.setRequestId(currentRequestId);
		APIRequestWorker.getInstance().addAPIRequest(haiVLRequester);
	}

	void getOld(RequestListener listener) {
		Logger.logMe("requesting page = " + oldPage);
		HaiVLRequester haiVLRequester = HaiVLRequester.getOld(oldPage, listener);
		currentRequestId = AppSettingParams.nextRequestId();
		haiVLRequester.setRequestId(currentRequestId);
		APIRequestWorker.getInstance().addAPIRequest(haiVLRequester);
	}

	private void doComment(final HaiBLMetalData blMetalData) {
		if (blMetalData != null) {
			FaceBookUtils.doViewComment(this, getApplication(), HaiVlCommentActivity.class, blMetalData.getDetailUrl());
		}

		// final Facebook facebook = new Facebook(GlobalData.FACEBOOK_APP_ID);
		// boolean isValid = SessionStore.restore(facebook, HaiVLActivity.this);
		// if (isValid) {
		// Logger.logMe("getAccessToken " + facebook.getAccessToken());
		// Logger.logMe("getAccessExpires " + facebook.getAccessExpires());
		// Intent intent = new Intent(getApplication(),
		// HaiVlCommentActivity.class);
		// if (blMetalData != null) {
		// intent.putExtra("IMAGE_ID", blMetalData.getDetailUrl());
		// }
		// startActivity(intent);
		// } else {
		// FaceBookUtils.doLoginFaceBook(this, facebook, new DialogListener() {
		//
		// public void onFacebookError(FacebookError e) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// public void onError(DialogError e) {
		// // TODO Auto-generated method stub
		//
		// }
		//
		// public void onComplete(Bundle values) {
		// if (facebook != null) {
		// // TODO Auto-generated method stub
		// Logger.logMe("getAccessToken " + facebook.getAccessToken());
		// Logger.logMe("getAccessExpires " + facebook.getAccessExpires());
		// SessionStore.save(facebook, HaiVLActivity.this);
		// Intent intent = new Intent(getApplication(),
		// HaiVlCommentActivity.class);
		// if (blMetalData != null) {
		// intent.putExtra("IMAGE_ID", blMetalData.getDetailUrl());
		// }
		// startActivity(intent);
		// }
		// }
		//
		// public void onCancel() {
		//
		// }
		// });
		// }
	}

	public void commicChanged(HaiBLMetalData blMetalData) {
		Logger.logMe(">>>>>>>>>>>>>>>>>>>>>>>>commicChanged");
		if (imageDescription != null) {
			imageDescription.setText(blMetalData.getTitleDescription());
		}
		if (commentView != null) {
			String comment = getResources().getString(R.string.comment_string);
			if (!blMetalData.getCommentCount().equals(""))
				comment = blMetalData.getCommentCount() + " " + comment;
			commentView.setText(comment);
		}
		if (videoFunction != null) {
			if (blMetalData.isVideo()) {
				videoFunction.setVisibility(View.VISIBLE);
			} else {
				videoFunction.setVisibility(View.INVISIBLE);
			}
		}
	}

	ViewPagerSupportImageView viewPager = null;
	AdsViewControl prView = null;
	LinearLayout loading = null;
	LinearLayout loadingError = null;
	LinearLayout videoFunction = null;
	TextView imageDescription = null;
	LinearLayout menuBar = null;
	TextView commentView = null;
	TextView btnShare = null;
	Button btnView = null;

	OnClickListener doComment = new OnClickListener() {

		public void onClick(View v) {
			doComment(imageComicAdapter.getCurrentData());
		}
	};

	OnClickListener viewVideo = new OnClickListener() {

		public void onClick(View v) {
			if (imageComicAdapter != null && imageComicAdapter.getCurrentData() != null) {
				String videoLink = imageComicAdapter.getCurrentData().getVideoLink();
				if (videoLink != null) {
					Logger.logMe("Link from server");
					Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(videoLink));
					startActivity(browserIntent);
				} else {
					String image = imageComicAdapter.getCurrentData().getImageUrl();
					if (image != null && image.indexOf("youtube") != -1) {
						String[] rs = image.split("/");
						if (rs.length > 0) {
							String id = rs[rs.length - 2];
							String url = "http://www.youtube.com/embed/" + id;
							Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
							startActivity(browserIntent);
						}
					}
				}
			}
		}
	};

	boolean isShowFunctionControl = true;
	OnClickListener onImageViewTouchTapConfirm = new OnClickListener() {

		public void onClick(View v) {

			if (isShowFunctionControl) {
				Animation animFadeOut = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out);
				topMenuBar.setAnimation(animFadeOut);
				tabHost.getTabWidget().setAnimation(animFadeOut);
				isShowFunctionControl = false;
				tabHost.getTabWidget().setVisibility(View.GONE);
				topMenuBar.setVisibility(View.GONE);
			} else {
				Animation animFadeIn = AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
				topMenuBar.setAnimation(animFadeIn);
				tabHost.getTabWidget().setAnimation(animFadeIn);
				isShowFunctionControl = true;
				tabHost.getTabWidget().setVisibility(View.VISIBLE);
				topMenuBar.setVisibility(View.VISIBLE);
			}

		}
	};

	RequestListener listener = new RequestListener() {

		public void onRequestFailed(String errorMsg, Request request) {
			runOnUiThread(new Runnable() {
				public void run() {
					imageComicAdapter.clearData();
					loading.setVisibility(View.GONE);
					loadingError.setVisibility(View.VISIBLE);

					doAdsByServer();
				}
			});
		}

		public void onRequestComplete(Request request) {
			// TODO Auto-generated method stub
			if (request instanceof HaiVLRequester && currentRequestId == request.getRequestId()) {
				ArrayList<HaiBLMetalData> datas = ((HaiVLRequester) request).getDataList();
				imageComicAdapter.setNewData(datas);

				runOnUiThread(new Runnable() {
					public void run() {
						if (isShowFunctionControl) {
							menuBar.setVisibility(View.VISIBLE);
							imageDescription.setVisibility(View.VISIBLE);
						} else {
							menuBar.setVisibility(View.GONE);
							imageDescription.setVisibility(View.GONE);
						}

						btnShare.setVisibility(View.GONE);
						commentView.setVisibility(View.GONE);
						
						loading.setVisibility(View.GONE);
						viewPager.setVisibility(View.VISIBLE);
						imageComicAdapter.notifyDataSetChanged();
						imageComicAdapter.onPageSelected(0);

						doAdsByServer();

					}
				});
			}

		}
	};

	LinearLayout loadingFinalPage = null;
	
	public void onTabChanged(String tag) {

		View view = tabHost.getCurrentView();
		loadingFinalPage = (LinearLayout) view.findViewById(R.id.loadingFinalPage);
		viewPager = (ViewPagerSupportImageView) view.findViewById(R.id.view_pager);
		
		loading = (LinearLayout) view.findViewById(R.id.loadingpage);
		loadingError = (LinearLayout) view.findViewById(R.id.loadingError);
		videoFunction = (LinearLayout) view.findViewById(R.id.videoFunction);
		imageDescription = (TextView) view.findViewById(R.id.imageDescription);
		
		menuBar = (LinearLayout) view.findViewById(R.id.menubar);
		
		btnShare = (Button) view.findViewById(R.id.btnShare);		
		commentView = (TextView) view.findViewById(R.id.commentView);
		
		prView = (AdsViewControl) view.findViewById(R.id.prview);
		commentView.setOnClickListener(doComment);
		
		btnView = (Button) view.findViewById(R.id.doViewVideoFunction);
		btnView.setOnClickListener(viewVideo);
//		viewPager.setOffscreenPageLimit(1);

		
		viewPager.setVisibility(View.INVISIBLE);
		loading.setVisibility(View.VISIBLE);
		menuBar.setVisibility(View.INVISIBLE);
		loadingError.setVisibility(View.INVISIBLE);
		prView.setVisibility(View.INVISIBLE);

		currentTab = tag;

		if (imageComicAdapter == null) {
			imageComicAdapter = new ImagePagerAdapter(this);
			imageComicAdapter.setOnFinalPage(this);
			imageComicAdapter.setComicChanged(this);
			imageComicAdapter.setOnClickImageViewSingerTapListener(onImageViewTouchTapConfirm);
		}

		imageComicAdapter.clearData();
		viewPager.setAdapter(imageComicAdapter);
		viewPager.setOnPageChangeListener(imageComicAdapter);

		// khi doi tab can reset lai so page
		// cached lai nhu the nao
		if ("new".equals(tag)) {
			getNew(listener);
		} else if ("hot".equals(tag)) {
			getHot(listener);
		} else if ("old".equals(tag)) {
			getOld(listener);
		}
	}

	private int countAds = 0;

	public void onFinalPage() {
		loadingFinalPage.setVisibility(View.VISIBLE);
		countAds++;
		System.out.println("onFinalPage " + countAds);
//		if (countAds >= 2) {
			countAds = 0;
			System.out.println("onFinalPage doAdsByServerdoAdsByServerdoAdsByServerdoAdsByServerdoAdsByServer");
			doAdsByServer();
//		}
		RequestListener listener = new RequestListener() {

			public void onRequestFailed(String errorMsg, Request request) {
				// TODO Auto-generated method stub
				Logger.logMe(">>>>Fail");
				runOnUiThread(new Runnable() {
					public void run() {
						loadingFinalPage.setVisibility(View.GONE);
					}
				});
			}

			public void onRequestComplete(Request request) {
				// TODO Auto-generated method stub
				if (request instanceof HaiVLRequester && currentRequestId == request.getRequestId()) {
					final ArrayList<HaiBLMetalData> datas = ((HaiVLRequester) request).getDataList();
					runOnUiThread(new Runnable() {
						public void run() {
							loadingFinalPage.setVisibility(View.GONE);
							if (imageComicAdapter != null) {
								imageComicAdapter.setMetalData(datas);
								imageComicAdapter.notifyDataSetChanged();
							}
						}
					});
				}
			}
		};
		if ("new".equals(currentTab)) {
			newPage++;
			getNew(listener);
		} else if ("hot".equals(currentTab)) {
			hotPage++;
			getHot(listener);
		} else if ("old".equals(currentTab)) {
			oldPage++;
			getOld(listener);
		}
	}

	public void onComment(HaiBLMetalData data) {
		if (data != null) {
			Logger.logMe("getTitleDescription = " + data.getTitleDescription());
			Logger.logMe("getCommentCount = " + data.getCommentCount());
			doComment(data);
		}

	}

	public void onLike(HaiBLMetalData data) {
		// TODO Auto-generated method stub

	}

	public void onFinalItem(HaiBLMetalData data) {
		// TODO Auto-generated method stub

	}
}
